package com.objk.admin.security.filter;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

@Deprecated
public class CustomAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) {

        if (CollectionUtils.isEmpty(configAttributes)) {
            return;
        }

        if (CollectionUtils.isNotEmpty(configAttributes)) {
            Iterator<ConfigAttribute> configAttributeIterator = configAttributes.iterator();

            while (configAttributeIterator.hasNext()) {
                ConfigAttribute configAttribute = configAttributeIterator.next();
                String needPermission = configAttribute.getAttribute();
                System.out.println("访问" + object.toString() + "需要的权限是：" + needPermission);
                for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                    if (grantedAuthority.getAuthority().equals(needPermission)) {
                        //匹配到有对应角色,则允许通过
                        return;
                    }
                }
            }

            throw new AccessDeniedException("无权访问");
        }
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
